#!/bin/sh

source ${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_conda_pytorch.sh

export CURRENT_APP_PATH="${LMD_APPS_DIR}/ComfyUI"
echo $CURRENT_APP_PATH
mkdir -p $CURRENT_APP_PATH

if [ -d "$CURRENT_APP_PATH" ]; then
    echo "App Dir: "$CURRENT_APP_PATH
else
    echo "Error, App Dir dose not exist, please retry. "$CURRENT_APP_PATH
    exit 1
fi

export GIT_HOST=${GITHUB_PROXY}"https://github.com"
export GIT_DEPTH_PARAM="--depth=1"

function clone_comfyui {
    git clone ${GIT_HOST}/comfyanonymous/ComfyUI $CURRENT_APP_PATH $GIT_DEPTH_PARAM
    cd ${CURRENT_APP_PATH}
}

clone_comfyui

git reset --hard
git pull $GIT_DEPTH_PARAM --force --no-rebase

exit_code=$?
if [ $exit_code -eq 128 ]; then
    echo "Pull error: $exit_code. Remove the ComfyUI repo and clone it again."
    echo "remove dir: "$CURRENT_APP_PATH
    rm -rf $CURRENT_APP_PATH
    clone_comfyui
fi

conda install -y conda-forge::huggingface_hub
pip install -r requirements.txt

echo 'Install ComfyUI-Manager'
cd ${CURRENT_APP_PATH}/custom_nodes
export COMFYUI_MANAGER_DIR="${CURRENT_APP_PATH}/custom_nodes/ComfyUI-Manager"

function clone_comfyui_manager {
   git clone ${GIT_HOST}/ltdrdata/ComfyUI-Manager ${COMFYUI_MANAGER_DIR} ${GIT_DEPTH_PARAM}
   cd ${COMFYUI_MANAGER_DIR}
}

clone_comfyui_manager

git reset --hard
git pull $GIT_DEPTH_PARAM --force --no-rebase

exit_code=$?
if [ $exit_code -eq 128 ]; then
    echo "Pull error: $exit_code. Remove the ComfyUI Manager repo and clone it again."
    echo "remove dir: "$COMFYUI_MANAGER_DIR
    rm -rf $COMFYUI_MANAGER_DIR
    clone_comfyui_manager
fi

